<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 外部就业经历模型
 * 管理员工在其他公司的就业经历
 */
class ExternalExperience extends Model
{
    use HasFactory;

    /**
     * 表名
     */
    protected $table = 'external_experiences';

    /**
     * 可填充字段
     */
    protected $fillable = [
        'employee_id',
        'company_name',
        'company_type',
        'company_industry',
        'company_size',
        'company_description',
        'position_title',
        'position_level',
        'department',
        'job_responsibilities',
        'job_achievements',
        'employment_type',
        'is_remote',
        'work_location',
        'start_date',
        'end_date',
        'is_current',
        'work_years',
        'reason_for_leaving',
        'salary',
        'salary_currency',
        'salary_type',
        'benefits',
        'reporting_to',
        'team_size',
        'has_direct_reports',
        'skills_used',
        'technologies_used',
        'tools_used',
        'performance_rating',
        'performance_comments',
        'reference_name',
        'reference_position',
        'reference_contact',
        'reference_comments',
        'is_verified',
        'verified_by',
        'verified_at',
        'attachments',
        'is_active',
        'sort_order',
    ];

    /**
     * 字段类型转换
     */
    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'verified_at' => 'date',
        'is_current' => 'boolean',
        'is_remote' => 'boolean',
        'is_verified' => 'boolean',
        'is_active' => 'boolean',
        'has_direct_reports' => 'boolean',
        'salary' => 'decimal:2',
        'benefits' => 'array',
        'skills_used' => 'array',
        'technologies_used' => 'array',
        'attachments' => 'array',
    ];

    /**
     * 日期字段
     */
    protected $dates = [
        'start_date',
        'end_date',
        'verified_at',
        'created_at',
        'updated_at',
    ];

    // ============ 常量定义 ============

    public const COMPANY_PRIVATE = 'private';
    public const COMPANY_PUBLIC = 'public';
    public const COMPANY_FOREIGN = 'foreign';
    public const COMPANY_GOVERNMENT = 'government';

    public const SIZE_STARTUP = 'startup';
    public const SIZE_SMALL = 'small';
    public const SIZE_MEDIUM = 'medium';
    public const SIZE_LARGE = 'large';

    public const EMPLOYMENT_FULL_TIME = 'full_time';
    public const EMPLOYMENT_PART_TIME = 'part_time';
    public const EMPLOYMENT_CONTRACT = 'contract';
    public const EMPLOYMENT_FREELANCE = 'freelance';
    public const EMPLOYMENT_INTERNSHIP = 'internship';

    public const SALARY_MONTHLY = 'monthly';
    public const SALARY_ANNUAL = 'annual';
    public const SALARY_HOURLY = 'hourly';

    // ============ 关联关系 ============

    /**
     * 关联员工
     */
    public function employee(): BelongsTo
    {
        return $this->belongsTo(Employee::class);
    }

    // ============ 访问器 ============

    /**
     * 获取公司类型标签
     */
    public function getCompanyTypeLabelAttribute(): string
    {
        return match($this->company_type) {
            self::COMPANY_PRIVATE => '私营企业',
            self::COMPANY_PUBLIC => '上市公司',
            self::COMPANY_FOREIGN => '外资企业',
            self::COMPANY_GOVERNMENT => '政府机构',
            default => $this->company_type ?? '未知'
        };
    }

    /**
     * 获取公司规模标签
     */
    public function getCompanySizeLabelAttribute(): string
    {
        return match($this->company_size) {
            self::SIZE_STARTUP => '创业公司',
            self::SIZE_SMALL => '小型企业',
            self::SIZE_MEDIUM => '中型企业',
            self::SIZE_LARGE => '大型企业',
            default => $this->company_size ?? '未知'
        };
    }

    /**
     * 获取工作类型标签
     */
    public function getEmploymentTypeLabelAttribute(): string
    {
        return match($this->employment_type) {
            self::EMPLOYMENT_FULL_TIME => '全职',
            self::EMPLOYMENT_PART_TIME => '兼职',
            self::EMPLOYMENT_CONTRACT => '合同工',
            self::EMPLOYMENT_FREELANCE => '自由职业',
            self::EMPLOYMENT_INTERNSHIP => '实习',
            default => $this->employment_type ?? '未知'
        };
    }

    /**
     * 获取薪资类型标签
     */
    public function getSalaryTypeLabelAttribute(): string
    {
        return match($this->salary_type) {
            self::SALARY_MONTHLY => '月薪',
            self::SALARY_ANNUAL => '年薪',
            self::SALARY_HOURLY => '时薪',
            default => $this->salary_type ?? '未知'
        };
    }

    /**
     * 获取工作年限
     */
    public function getWorkYearsFormattedAttribute(): string
    {
        if (!$this->work_years) {
            return '未知';
        }

        if ($this->work_years < 12) {
            return $this->work_years . '个月';
        }

        $years = floor($this->work_years / 12);
        $months = $this->work_years % 12;

        $result = $years . '年';
        if ($months > 0) {
            $result .= $months . '个月';
        }

        return $result;
    }

    /**
     * 获取薪资信息
     */
    public function getSalaryInfoAttribute(): string
    {
        if (!$this->salary) {
            return '薪资未公开';
        }

        $salary = number_format($this->salary, 0);
        $currency = $this->salary_currency ?? 'CNY';
        $type = $this->salary_type_label;

        return "{$salary} {$currency}/{$type}";
    }

    /**
     * 获取公司信息
     */
    public function getCompanyInfoAttribute(): string
    {
        $info = $this->company_name;

        if ($this->company_type) {
            $info .= " ({$this->company_type_label})";
        }

        if ($this->company_size) {
            $info .= " - {$this->company_size_label}";
        }

        return $info;
    }

    /**
     * 获取工作地点信息
     */
    public function getWorkLocationInfoAttribute(): string
    {
        if ($this->is_remote) {
            return '远程工作';
        }

        return $this->work_location ?? '未填写';
    }

    /**
     * 获取团队规模信息
     */
    public function getTeamInfoAttribute(): string
    {
        if (!$this->team_size) {
            return '团队规模未知';
        }

        if ($this->has_direct_reports) {
            return "管理 {$this->team_size} 人团队";
        }

        return "{$this->team_size} 人团队";
    }

    /**
     * 获取技能列表
     */
    public function getSkillsListAttribute(): string
    {
        if (!$this->skills_used) {
            return '未填写';
        }

        return implode(', ', $this->skills_used);
    }

    /**
     * 获取技术栈列表
     */
    public function getTechnologiesListAttribute(): string
    {
        if (!$this->technologies_used) {
            return '未填写';
        }

        return implode(', ', $this->technologies_used);
    }

    // ============ 作用域 ============

    /**
     * 当前工作作用域
     */
    public function scopeCurrent($query)
    {
        return $query->where('is_current', true);
    }

    /**
     * 历史工作作用域
     */
    public function scopeHistorical($query)
    {
        return $query->where('is_current', false);
    }

    /**
     * 全职工作作用域
     */
    public function scopeFullTime($query)
    {
        return $query->where('employment_type', self::EMPLOYMENT_FULL_TIME);
    }

    /**
     * 按公司筛选作用域
     */
    public function scopeByCompany($query, $companyName)
    {
        return $query->where('company_name', 'like', "%{$companyName}%");
    }

    /**
     * 按行业筛选作用域
     */
    public function scopeByIndustry($query, $industry)
    {
        return $query->where('company_industry', $industry);
    }

    /**
     * 按职位筛选作用域
     */
    public function scopeByPosition($query, $position)
    {
        return $query->where('position_title', 'like', "%{$position}%");
    }

    /**
     * 按时间范围筛选作用域
     */
    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('start_date', [$startDate, $endDate]);
    }

    /**
     * 远程工作筛选作用域
     */
    public function scopeRemote($query)
    {
        return $query->where('is_remote', true);
    }

    /**
     * 已验证作用域
     */
    public function scopeVerified($query)
    {
        return $query->where('is_verified', true);
    }

    // ============ 业务方法 ============

    /**
     * 验证经历
     */
    public function verify(string $verifiedBy): bool
    {
        $this->is_verified = true;
        $this->verified_by = $verifiedBy;
        $this->verified_at = now();

        return $this->save();
    }

    /**
     * 取消验证
     */
    public function unverify(): bool
    {
        $this->is_verified = false;
        $this->verified_by = null;
        $this->verified_at = null;

        return $this->save();
    }

    /**
     * 设置为当前工作
     */
    public function setAsCurrent(): bool
    {
        $this->is_current = true;
        $this->end_date = null;

        return $this->save();
    }

    /**
     * 结束当前工作
     */
    public function endWork(\DateTime $endDate, ?string $reason = null): bool
    {
        $this->is_current = false;
        $this->end_date = $endDate;
        $this->reason_for_leaving = $reason;

        return $this->save();
    }

    /**
     * 更新薪资信息
     */
    public function updateSalary(float $salary, string $currency = 'CNY', string $type = self::SALARY_MONTHLY): bool
    {
        $this->salary = $salary;
        $this->salary_currency = $currency;
        $this->salary_type = $type;

        return $this->save();
    }

    /**
     * 更新福利信息
     */
    public function updateBenefits(array $benefits): bool
    {
        $this->benefits = $benefits;
        return $this->save();
    }

    /**
     * 添加技能
     */
    public function addSkill(string $skill): bool
    {
        $skills = $this->skills_used ?? [];
        if (!in_array($skill, $skills)) {
            $skills[] = $skill;
            $this->skills_used = $skills;
            return $this->save();
        }
        return true;
    }

    /**
     * 移除技能
     */
    public function removeSkill(string $skill): bool
    {
        $skills = $this->skills_used ?? [];
        $skills = array_diff($skills, [$skill]);
        $this->skills_used = array_values($skills);
        return $this->save();
    }

    /**
     * 添加技术
     */
    public function addTechnology(string $technology): bool
    {
        $technologies = $this->technologies_used ?? [];
        if (!in_array($technology, $technologies)) {
            $technologies[] = $technology;
            $this->technologies_used = $technologies;
            return $this->save();
        }
        return true;
    }

    /**
     * 移除技术
     */
    public function removeTechnology(string $technology): bool
    {
        $technologies = $this->technologies_used ?? [];
        $technologies = array_diff($technologies, [$technology]);
        $this->technologies_used = array_values($technologies);
        return $this->save();
    }

    // ============ 静态方法 ============

    /**
     * 计算工作年限
     */
    public static function calculateWorkYears(\DateTime $startDate, ?\DateTime $endDate = null): float
    {
        $endDate = $endDate ?: now();
        return $startDate->diffInMonths($endDate);
    }

    /**
     * 验证工作经历数据
     */
    public static function validateExperienceData(array $data): array
    {
        $errors = [];

        // 必填字段验证
        $requiredFields = ['employee_id', 'company_name', 'position_title', 'employment_type', 'start_date'];
        foreach ($requiredFields as $field) {
            if (empty($data[$field])) {
                $errors[] = "{$field} 字段不能为空";
            }
        }

        // 公司类型验证
        $validCompanyTypes = [self::COMPANY_PRIVATE, self::COMPANY_PUBLIC, self::COMPANY_FOREIGN, self::COMPANY_GOVERNMENT];
        if (!empty($data['company_type']) && !in_array($data['company_type'], $validCompanyTypes)) {
            $errors[] = "无效的公司类型";
        }

        // 公司规模验证
        $validSizes = [self::SIZE_STARTUP, self::SIZE_SMALL, self::SIZE_MEDIUM, self::SIZE_LARGE];
        if (!empty($data['company_size']) && !in_array($data['company_size'], $validSizes)) {
            $errors[] = "无效的公司规模";
        }

        // 工作类型验证
        $validEmploymentTypes = [self::EMPLOYMENT_FULL_TIME, self::EMPLOYMENT_PART_TIME, self::EMPLOYMENT_CONTRACT, self::EMPLOYMENT_FREELANCE, self::EMPLOYMENT_INTERNSHIP];
        if (!empty($data['employment_type']) && !in_array($data['employment_type'], $validEmploymentTypes)) {
            $errors[] = "无效的工作类型";
        }

        // 薪资验证
        if (!empty($data['salary']) && (!is_numeric($data['salary']) || $data['salary'] <= 0)) {
            $errors[] = "薪资必须是有效的正数";
        }

        // 团队规模验证
        if (!empty($data['team_size']) && (!is_numeric($data['team_size']) || $data['team_size'] < 0)) {
            $errors[] = "团队规模必须是有效的非负数";
        }

        // 时间验证
        if (!empty($data['start_date']) && !empty($data['end_date'])) {
            $startDate = strtotime($data['start_date']);
            $endDate = strtotime($data['end_date']);

            if ($startDate && $endDate && $startDate >= $endDate) {
                $errors[] = "结束时间必须晚于开始时间";
            }
        }

        return $errors;
    }

    /**
     * 获取行业列表
     */
    public static function getIndustryOptions(): array
    {
        return [
            'technology' => '科技',
            'finance' => '金融',
            'healthcare' => '医疗',
            'education' => '教育',
            'manufacturing' => '制造业',
            'retail' => '零售',
            'consulting' => '咨询',
            'government' => '政府',
            'non_profit' => '非营利',
            'other' => '其他',
        ];
    }

    /**
     * 获取职位等级列表
     */
    public static function getPositionLevelOptions(): array
    {
        return [
            'entry' => '初级',
            'junior' => '初级',
            'senior' => '高级',
            'lead' => '资深',
            'manager' => '经理',
            'senior_manager' => '高级经理',
            'director' => '总监',
            'senior_director' => '高级总监',
            'vp' => '副总裁',
            'c_suite' => 'C级高管',
        ];
    }
}
